#include "gearcontrol.h"
#include <QDebug>

GearControl::GearControl(QGraphicsItem *parent)
    : QGraphicsObject(parent)
{
    setFlag(ItemIsMovable, false);
    setFlag(ItemIsSelectable, true);
    setCacheMode(DeviceCoordinateCache);
}

QRectF GearControl::boundingRect() const
{
    return QRectF(-50, -100, 100, 200);  // 档位按钮区域大小
}

void GearControl::paint(QPainter *painter,
                        const QStyleOptionGraphicsItem *,
                        QWidget *)
{
    painter->setRenderHint(QPainter::Antialiasing);

    // 绘制档位按钮
    painter->setPen(QPen(Qt::black, 2));
    painter->setBrush(Qt::lightGray);

    // 前进按钮
    painter->drawRect(-40, -90, 80, 40);
    painter->drawText(QRectF(-40, -90, 80, 40), Qt::AlignCenter, "前进");

    // 倒车按钮
    painter->drawRect(-40, -40, 80, 40);
    painter->drawText(QRectF(-40, -40, 80, 40), Qt::AlignCenter, "后退");

    // 驻车按钮
    painter->drawRect(-40, 10, 80, 40);
    painter->drawText(QRectF(-40, 10, 80, 40), Qt::AlignCenter, "驻车");

    // 手刹按钮
    painter->drawRect(-40, 60, 80, 40);
    painter->drawText(QRectF(-40, 60, 80, 40), Qt::AlignCenter, "手刹");
}

void GearControl::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        handleButtonClick(event->pos());
    }
    QGraphicsObject::mousePressEvent(event);
}

void GearControl::handleButtonClick(const QPointF &pos)
{
    KeyValue keyvalue = none;
    // 判断点击的按钮
    if (QRectF(-40, -90, 80, 40).contains(pos)) {
        keyvalue = up;
    } else if (QRectF(-40, -40, 80, 40).contains(pos)) {
        keyvalue = down;
    } else if (QRectF(-40, 10, 80, 40).contains(pos)) {
        keyvalue = park;
    } else if (QRectF(-40, 60, 80, 40).contains(pos)) {
        keyvalue = stop;
    }
    emit gearCommand(keyvalue);
}
